package com.starblink.comment.ui

import android.app.Activity
import android.view.View
import androidx.core.view.isNotEmpty
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.util.CommUtils
import com.starblink.comment.PostCommentVM
import com.starblink.comment.adapter.CommentMoreHolder
import com.starblink.comment.adapter.ItemCommentHolder
import com.starblink.comment.adapter.ItemReplyCommentHolder
import com.starblink.comment.bean.PostComment
import com.starblink.comment.bean.ReplyPostComment
import com.starblink.comment.databinding.DialogCommentListBinding
import com.starblink.comment.databinding.ItemMoreCommentBinding

/**
 * 内容评论列表弹窗
 */
class CommentPostListDialog(
    val context: Activity,
    val postId: String,
    var postContentType: String,
    private var commentNum: Int,
    val listener: () -> Unit///添加评论回调){}
) : BaseBottomSheetFragment() {

    lateinit var viewBinding: DialogCommentListBinding
    lateinit var viewModel: PostCommentVM

    override fun getBindingRootView(): View {
        viewBinding = DialogCommentListBinding.inflate(layoutInflater)
        return viewBinding.root
    }

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mList.value!!).apply {
            addVhDelegate {
                ItemCommentHolder(
                    it,
                    { replyCommentId,
                      replyCommentName,
                      parentCommentId ->
                        replyComment(
                            replyCommentId,
                            replyCommentName,
                            parentCommentId
                        )
                    }) { commentId, pos ->
                    deleteComment(commentId, pos)
                }
            }
            addVhDelegate {
                ItemReplyCommentHolder(
                    it, { replyCommentId,
                          replyCommentName,
                          parentCommentId ->
                        replyComment(
                            replyCommentId,
                            replyCommentName,
                            parentCommentId
                        )
                    }, { commentId, pos ->
                        deleteComment(commentId, pos)
                    })
            }
            addVhDelegate {
                CommentMoreHolder(
                    ItemMoreCommentBinding.inflate(it.inflater, it, false)
                ) {///加载更多子评论
                        commentId, commentIdx ->
                    if (it.isNotEmpty()) {
                        viewModel.getSecondCommentList(commentId, commentIdx)
                    }
                }
            }
        }
    }

    private fun deleteComment(commentId: String, pos: Int) {
        ConfirmDialog.Builder(context)
            .setTitle(CommUtils.getString(com.starblink.basic.style.R.string.DETAILCONFIRM))
            .setMessage("")
            .setSureButton(
                textId = com.starblink.basic.style.R.string.confirm
            ) { p0, p1 ->
                run {
                    viewModel.deleteComment(commentId, pos)
                    p0.dismiss()
                }
            }
            .setCanCancel(true)
            .create().show()
    }

    ///回复评论
    private fun replyComment(
        replyCommentId: String,
        replyCommentName: String,
        parentCommentId: String
    ) {
        LoginCheckInterceptor.check2Login(context) {
            val inputTextMsgDialog =
                PostCommentDialog(context, com.starblink.android.basic.R.style.dialog_center);
            inputTextMsgDialog.setTextSendListener {
                if (it != null) {
                    val comment = it.toJson().toBean<ReplyPostComment>()
                    var insertIndex = 0
                    for (i in viewModel.mList.value!!.indices) {
                        val comment = viewModel.mList.value!![i]
                        if (comment is PostComment && comment.id == parentCommentId) {
                            insertIndex = i + 1
                            break
                        }
                    }
                    viewModel.mList.value?.add(insertIndex, comment)
                    viewModel.mList.value = viewModel.mList.value
                    addCommentSync()
                }
            }
            inputTextMsgDialog.setId(postId)
            inputTextMsgDialog.setContentType(postContentType)
            inputTextMsgDialog.setHint("reply to $replyCommentName")
            inputTextMsgDialog.setReplyId(replyCommentId)
            inputTextMsgDialog.show()
        }
    }

    private fun addCommentSync(
    ) {
        commentNum += 1
        viewBinding.tvCommentNum.text = "All comments·$commentNum"
        listener.invoke()
    }

    override fun initView() {
        viewModel = ViewModelProvider(requireActivity())[PostCommentVM::class.java]
        viewModel.postId = postId
        viewModel.getCommentList()

        setPeekPercent(0.85)
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.getCommentList(isFirst = false)
        }
        viewBinding.recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        viewBinding.recyclerView.adapter = adapter//单位px

        setView()

        observeData()
    }

    private fun setView() {
        viewBinding.close.click {
            dismiss()
        }
        viewBinding.tvCommentNum.text = "All comments·$commentNum"

        ///增加评论
        viewBinding.tvAdd.click {
            LoginCheckInterceptor.check2Login(context) {
                val inputTextMsgDialog =
                    PostCommentDialog(context, com.starblink.android.basic.R.style.dialog_center)
                inputTextMsgDialog.setTextSendListener {
                    if (it != null) {
                        val comment = it.toJson().toBean<PostComment>()
                        viewModel.mList.value?.add(0, comment)
                        viewModel.mList.value = viewModel.mList.value
                        addCommentSync()
                    }
                }
                inputTextMsgDialog.setId(postId)
                inputTextMsgDialog.setContentType(postContentType)
                inputTextMsgDialog.show()
            }
        }
    }

    private fun observeData() {
        viewModel.mList.observe(this) {
            if (viewModel.mList.value!!.isNotEmpty()) {
                adapter.notifyDataSetChanged()

                viewBinding.empty.visibleOrGone(false) {

                }
            }
        }

        viewModel.mLoadActionLiveData.observe(this) {
            if (viewBinding.refresher.isLoading) {
                viewBinding.refresher.finishLoadMore()
            }
            viewBinding.empty.visibleOrGone(
                viewModel.mLoadActionLiveData.value == LoadAction(
                    LoadAction.STATE_NO_DATA
                )
            ) {

            }
        }
    }

}